package com.mall.controller;

import com.mall.utils.EmailUtil;
import com.mall.utils.SmsUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 信息发送
 */
@RestController
@RequestMapping("/send/sc")
public class SendController {
    @RequestMapping("/sms")
    public Map<String,Object>sms(@RequestParam(name = "mobiles[]")List<String>mobiles,
                                 @RequestParam(name = "templates")String template,
                                 HttpSession session){
        Map<String,Object>map=new HashMap<>();

        if("1".equals(template)){
            //删除session
            session.removeAttribute("mobileCode");
            String mobileCode=(new Random().nextInt(900000)+100000)+"";
            //设置session有效时间
            session.setMaxInactiveInterval(5*60);//秒为单位
            session.setAttribute("mobileCode",mobileCode);
            String datas[]={mobileCode,"5"};
            SmsUtil.sendSmsToMobile(mobiles,template,datas);

            map.put("msg","信息已发送");

        }
        return map;
    }

    @RequestMapping("/email")
    public Map<String,Object> email(@RequestParam(name = "emails[]")List<String> emails,
                                    @RequestParam(name = "type")String type){
        Map<String,Object> map=new HashMap<>();
        //集合转换为数组
        String es[]=new String[emails.size()];
        es=emails.toArray(es);
        map.put("is",false);
        if("forgetPwd".equals(type)) {
            try {
                String now = System.currentTimeMillis() + "";
                byte bs[] = now.getBytes("UTF-8");
                StringBuffer msg = new StringBuffer("复制以下链接到浏览器中完成验证：<br>")
                        .append("<a href='#'>http://127.0.0.1:8083/page/forgetVerify?")//TODO 临时ip地址
                        .append("code="+new BASE64Encoder().encode(bs))
                        .append("&")
                        .append("token=" +new BASE64Encoder().encode(es[0].getBytes(StandardCharsets.UTF_8)))
                        .append("</a>");

                boolean b = EmailUtil.sendEmail(es, msg.toString(), "分销商城后台邮箱找回密码");
               map.put("is",b);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return map;
    }
}
